package util;

import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.amazonaws.util.json.JSONObject;

import entities.Domain;
import entities.IPRange;

public class Utils {

	private static String couchDBURL = "http://ec2-54-83-110-203.compute-1.amazonaws.com/";
	private static Pattern pattern;
	private static Pattern emailPattern;
	private static Matcher matcher;
	private static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
			+ "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	static {
		pattern = Pattern.compile(IPADDRESS_PATTERN);
		emailPattern = Pattern.compile(EMAIL_PATTERN);
	}

	public static boolean isValidDomain(String domainName) {
		domainName = domainName.replaceAll("^(http://)*", "");
		domainName = domainName.replaceAll("^(https://)*", "");

		ResourceBundle resource = ResourceBundle.getBundle("extension_domain",
				new Locale("en"));
		String re_domain = domainName;

		if (!Pattern.matches(
				"^[a-zA-Z0-9-]+([.][a-zA-Z_0-9-]+)*([.][a-zA-Z]+)+", re_domain)) {
			return false;
		}

		String[] listDomain = resource.getString("domain").split(" ");
		for (int i = 0; i < listDomain.length; i++) {
			re_domain = re_domain
					.replaceAll("[.]{1}" + listDomain[i] + "$", "");
		}

		if (re_domain.length() != domainName.length()) {
			return true;
		}

		return false;
	}

	public static void putElasticSearch(Domain domain, String db) {
		try {
			URL url = new URL("http://54.81.98.71:9200/" + db + "/" + db + "/"
					+ domain.getName());
			HttpURLConnection httpCon = (HttpURLConnection) url
					.openConnection();
			httpCon.setDoOutput(true);
			httpCon.setConnectTimeout(10000);
			httpCon.setRequestMethod("PUT");

			OutputStreamWriter out = new OutputStreamWriter(
					httpCon.getOutputStream());

			Class<?> clazz = domain.getClass();
			JSONObject obj = new JSONObject();
			for (Field field : clazz.getDeclaredFields()) {
				try {
					String fi = "null";
					if (field.get(domain) != null) {
						fi = field.get(domain).toString();
					}
					obj.put(field.getName(), fi);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			out.write(obj.toString());
			out.flush();
			out.close();
			httpCon.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void putCouchDb(Domain domain, String db) {
		try {
			URL url = new URL(couchDBURL + db + "/" + domain.getName());
			HttpURLConnection httpCon = (HttpURLConnection) url
					.openConnection();
			httpCon.setDoOutput(true);
			httpCon.setRequestProperty("Content-Type :",
					"application/json; charset=UTF-8");
			httpCon.setRequestProperty("User-Agent :",
					"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
			httpCon.setRequestProperty("Accept :",
					"application/json, text/javascript, */*; q=0.01");
			httpCon.setRequestProperty("Accept-Language :", "en-US,en;q=0.5");
			httpCon.setRequestProperty("Accept-Encoding :", "gzip, deflate");
			httpCon.setRequestProperty("X-Requested-With :", "XMLHttpRequest");
			httpCon.setRequestProperty("Connection :", "keep-alive");
			httpCon.setRequestProperty("Cache-Control :", "must-revalidate");
			httpCon.setRequestMethod("PUT");

			String charset = "UTF-8";

			Class<?> clazz = domain.getClass();
			JSONObject obj = new JSONObject();
			for (Field field : clazz.getDeclaredFields()) {
				try {
					String fi = "null";
					if (field.get(domain) != null) {
						fi = field.get(domain).toString();
					}
					obj.put(field.getName(), fi);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			OutputStreamWriter out = new OutputStreamWriter(
					httpCon.getOutputStream(), charset);
			out.write(obj.toString());
			out.close();

			httpCon.getInputStream();
			putElasticSearch(domain, "mother_hacker");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void putCouchDbIPRange(IPRange ipRange, String db) {
		try {
			URL url = new URL(couchDBURL + db + "/" + ipRange.getId());
			HttpURLConnection httpCon = (HttpURLConnection) url
					.openConnection();
			httpCon.setDoOutput(true);
			httpCon.setRequestProperty("Content-Type :",
					"application/json; charset=UTF-8");
			httpCon.setRequestProperty("User-Agent :",
					"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
			httpCon.setRequestProperty("Accept :",
					"application/json, text/javascript, */*; q=0.01");
			httpCon.setRequestProperty("Accept-Language :", "en-US,en;q=0.5");
			httpCon.setRequestProperty("Accept-Encoding :", "gzip, deflate");
			httpCon.setRequestProperty("X-Requested-With :", "XMLHttpRequest");
			httpCon.setRequestProperty("Connection :", "keep-alive");
			httpCon.setRequestProperty("Cache-Control :", "must-revalidate");
			httpCon.setRequestMethod("PUT");

			String charset = "UTF-8";

			Class<?> clazz = ipRange.getClass();
			JSONObject obj = new JSONObject();
			for (Field field : clazz.getDeclaredFields()) {
				try {
					String fi = "null";
					if (field.get(ipRange) != null) {
						fi = field.get(ipRange).toString();
					}
					obj.put(field.getName(), fi);
				} catch (Exception e) {

				}
			}

			OutputStreamWriter out = new OutputStreamWriter(
					httpCon.getOutputStream(), charset);
			out.write(obj.toString());
			out.close();

			httpCon.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getDomain(String url) {
		url = url.toLowerCase().replaceAll("(http|https)+://", "")
				.replaceAll("^[\\w\\W]+[\\/]{2}", "")
				.replaceAll("[\\/]+[\\w\\W]*$", "")
				.replaceAll("[\\?]+[\\w\\W]*$", "")
				.replaceAll("[ !@#$%^&*?()\\[\\]{}+=,:;|\\\'\\\"/\\\\`~]+", "")
				.trim();
		return url;
	}

	public static boolean isIPAddress(String ip) {
		matcher = pattern.matcher(ip);
		return matcher.matches();
	}

	public static boolean isEmail(String email) {
		matcher = emailPattern.matcher(email);
		return matcher.matches();
	}

	public static Double ipToLong(String ipAddress) {
		Double result = 0.0;
		try {
			String[] ipAddressInArray = ipAddress.split("\\.");
			for (int i = 0; i < ipAddressInArray.length; i++) {

				int power = 3 - i;
				int ip = Integer.parseInt(ipAddressInArray[i]);
				result += ip * Math.pow(256, power);

			}
		} catch (Exception e) {
			e.printStackTrace();
			result = 0.0;
		}
		return result;
	}

	public static String longStringToIp(String iStr) {
		try {
			long i = Long.parseLong(iStr);
			return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
					+ ((i >> 8) & 0xFF) + "." + (i & 0xFF);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}

	public static String longToIp(long i) {
		try {
			return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
					+ ((i >> 8) & 0xFF) + "." + (i & 0xFF);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static IPRange checkIPInRange(Double ipLong) {
		IPRange obj = null;
		return obj;
	}

	public static String getDotVnWhois(String vnDomain) {	
		Domain temp = ConnectionHandle
				.fetchDomainByUrlThroughJsoup("https://powernet.vn/whois/"
						+ vnDomain);
		Document doc = Jsoup.parse(temp.getHtml());
		String whoisTemp = doc.select("blockquote").html();

		if (whoisTemp.contains("<br")) {
			whoisTemp = whoisTemp.replaceAll("<br />", "");
		}
		String[] tempArr = whoisTemp.split("\\n|\\r");
		whoisTemp = "";
		for (String string : tempArr) {
			whoisTemp += string.trim() + "\n";
		}
		if (whoisTemp != null && whoisTemp.length() > 0) {
			return whoisTemp;
		}
		return "";
	}

	public static String handleToBeGoodDomain(String name) {
		name = name.replaceAll("^(http://)*", "")
				.replaceAll("^(https://)*", "").replaceAll("/", "")
				.replaceAll("www.", "");
		ResourceBundle resource = ResourceBundle.getBundle("language_en",
				new Locale("en"));
		String[] listDomain = resource.getString("domain").split(" ");
		String last = "";
		int lengthLast = 0;
		for (int i = 0; i < listDomain.length; i++) {
			if (name.contains("." + listDomain[i])) {
				if (listDomain[i].length() > lengthLast) {
					lengthLast = listDomain[i].length();
					last = listDomain[i];
				}
			}
		}
		name = name.replace("." + last, "");
		if (name.contains(".")) {
			String[] tempArray = name.split("\\.");
			name = tempArray[tempArray.length - 1];
		}
		return name.trim() + "." + last.trim();
	}
}
